#region Copyright Jonathan Quiros

//	
// All rights are reserved. Reproduction or transmission in whole or in 
// part, in any form or by any means, electronic, mechanical or otherwise, 
// is prohibited without the prior written consent of the copyright owner.
//
// Filename: PlayersLogic.cs
//

#endregion

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Ids.Utils;
using Ids.Web.Listing;
using Novagoal.Models;
using Novagoal.Models.Utils;
using Novagoal.Repositories;

namespace Novagoal.Logic
{
    public class PlayersLogic : BaseLogic
    {
        #region CONSTANTS

        #endregion

        #region PROPERTIES

        private readonly IPlayersRepository _playersRepository;

        #endregion

        #region PUBLIC METHODS

        public PlayersLogic(IPlayersRepository playersRepository)
        {
            _playersRepository = playersRepository;
        }

        public PlayerList GetPlayers(NameValueCollection filters, string sort, string direction, int currentPage, int pageSize)
        {
            PlayerListSortField sortField;
            SortDirectionType sortDirection;
            Dictionary<PlayerListFilter, string> filterList;

            try
            {
                //Sorting based on parameters
                sortField = sort.ToEnumValue<PlayerListSortField>();
                sortDirection = direction.ToEnumValue<SortDirectionType>();
                filterList = ParseFilters<PlayerListFilter>(filters);
            }
            catch
            {
                //Default Sorting
                filterList = null;
                sortField = PlayerListSortField.Name;
                sortDirection = SortDirectionType.Ascending;
            }

            var items = _playersRepository.GetPlayers(filterList, sortField, sortDirection, currentPage, pageSize);
            var count = _playersRepository.GetTotalPlayers(filterList);

            var playerList = new PlayerList
            {
                CurrentPage = currentPage,
                Filters = filterList,
                Items = items,
                SortDirection = sortDirection,
                SortField = sortField
            };
            playerList.CalculatePagination(count, pageSize, currentPage);

            return playerList;
        }

        public void UpdateMvp(int playerId)
        {
            if(playerId != 0)
            {
                _playersRepository.UpdateMvp(playerId);
            }
        }

        public Player GetPlayer(int playerId)
        {
            return _playersRepository.GetPlayer(playerId);
        }

        public int SavePlayer(Player player)
        {
            return player.Id == 0 ? _playersRepository.AddPlayer(player) : _playersRepository.EditPlayer(player);
        }

        #endregion

        #region PRIVATE METHODS



        #endregion
    }
}